// 记忆翻牌游戏逻辑

// 游戏状态变量
let cards = [];
let flippedCards = [];
let matchedPairs = 0;
let totalPairs = 8; // 默认8对卡片
let score = 0;
let moves = 0;
let isGameRunning = false;
let isChecking = false;
let startTime;
let elapsedTime = 0;
let timerInterval;
let gameDuration;

// 卡片符号
const CARD_SYMBOLS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L'];

// 页面加载完成后初始化游戏
window.addEventListener('DOMContentLoaded', function() {
    initializeGame();
});

// 初始化游戏
function initializeGame() {
    // 获取游戏设置
    const settings = getGameSettings();
    gameDuration = settings.gameDuration;
    
    // 显示最高分
    document.getElementById('highScore').textContent = getHighScore('memory');
    
    // 创建卡片
    createCards();
    
    // 添加事件监听器
    document.getElementById('startBtn').addEventListener('click', startGame);
    document.getElementById('pauseBtn').addEventListener('click', togglePause);
    document.getElementById('resetBtn').addEventListener('click', resetGame);
}

// 创建卡片
function createCards() {
    const gameContainer = document.getElementById('memoryGame');
    gameContainer.innerHTML = '';
    
    // 重置游戏状态
    cards = [];
    flippedCards = [];
    matchedPairs = 0;
    score = 0;
    moves = 0;
    
    // 更新显示
    document.getElementById('score').textContent = score;
    document.getElementById('moves').textContent = moves;
    document.getElementById('timer').textContent = formatTime(elapsedTime);
    
    // 创建卡片数组
    const symbols = CARD_SYMBOLS.slice(0, totalPairs);
    // 每种符号添加两个卡片（一对）
    symbols.forEach(symbol => {
        cards.push({ symbol: symbol, matched: false });
        cards.push({ symbol: symbol, matched: false });
    });
    
    // 随机排序卡片
    shuffleArray(cards);
    
    // 创建DOM元素
    cards.forEach((card, index) => {
        const cardElement = document.createElement('div');
        cardElement.className = 'memory-card';
        cardElement.dataset.index = index;
        
        cardElement.innerHTML = `
            <div class="memory-card-inner">
                <div class="memory-card-front">?</div>
                <div class="memory-card-back">${card.symbol}</div>
            </div>
        `;
        
        cardElement.addEventListener('click', () => handleCardClick(index));
        gameContainer.appendChild(cardElement);
    });
}

// 洗牌算法
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}

// 开始游戏
function startGame() {
    if (isGameRunning) return;
    
    isGameRunning = true;
    startTime = Date.now() - elapsedTime * 1000;
    
    // 更新按钮状态
    document.getElementById('startBtn').disabled = true;
    document.getElementById('pauseBtn').disabled = false;
    
    // 启动计时器
    timerInterval = setInterval(updateTimer, 1000);
    
    // 重置卡片状态但保持布局
    const cardElements = document.querySelectorAll('.memory-card');
    cardElements.forEach(element => {
        element.classList.remove('flipped', 'matched');
    });
    
    cards.forEach(card => {
        card.matched = false;
    });
    
    flippedCards = [];
    matchedPairs = 0;
    
    showMessage('游戏开始！', 'success');
}

// 处理卡片点击
function handleCardClick(index) {
    // 如果游戏未运行，不处理点击
    if (!isGameRunning) return;
    
    // 如果正在检查配对，不处理点击
    if (isChecking) return;
    
    const card = cards[index];
    const cardElement = document.querySelector(`.memory-card[data-index="${index}"]`);
    
    // 如果卡片已经匹配或已经翻转，不处理点击
    if (card.matched || cardElement.classList.contains('flipped')) {
        return;
    }
    
    // 如果已经翻了两张卡片，不处理点击
    if (flippedCards.length >= 2) {
        return;
    }
    
    // 翻转卡片
    cardElement.classList.add('flipped');
    flippedCards.push({ index, symbol: card.symbol });
    
    // 如果翻了两张卡片，检查是否匹配
    if (flippedCards.length === 2) {
        moves++;
        document.getElementById('moves').textContent = moves;
        
        checkMatch();
    }
}

// 检查卡片是否匹配
function checkMatch() {
    isChecking = true;
    
    const [firstCard, secondCard] = flippedCards;
    
    if (firstCard.symbol === secondCard.symbol) {
        // 卡片匹配
        matchCards(firstCard.index, secondCard.index);
    } else {
        // 卡片不匹配
        setTimeout(() => {
            unflipCards(firstCard.index, secondCard.index);
        }, 1000);
    }
}

// 处理匹配的卡片
function matchCards(firstIndex, secondIndex) {
    // 更新卡片状态
    cards[firstIndex].matched = true;
    cards[secondIndex].matched = true;
    
    // 添加匹配样式
    const firstCardElement = document.querySelector(`.memory-card[data-index="${firstIndex}"]`);
    const secondCardElement = document.querySelector(`.memory-card[data-index="${secondIndex}"]`);
    
    firstCardElement.classList.add('matched');
    secondCardElement.classList.add('matched');
    
    // 增加匹配计数和分数
    matchedPairs++;
    score += 100; // 匹配成功加100分
    
    // 计算步数奖励（步数越少奖励越多）
    const moveBonus = Math.max(50 - moves * 2, 10);
    score += moveBonus;
    
    document.getElementById('score').textContent = score;
    
    // 清空已翻转卡片数组
    flippedCards = [];
    isChecking = false;
    
    // 检查游戏是否完成
    if (matchedPairs === totalPairs) {
        gameComplete();
    }
}

// 处理不匹配的卡片
function unflipCards(firstIndex, secondIndex) {
    // 翻回卡片
    const firstCardElement = document.querySelector(`.memory-card[data-index="${firstIndex}"]`);
    const secondCardElement = document.querySelector(`.memory-card[data-index="${secondIndex}"]`);
    
    firstCardElement.classList.remove('flipped');
    secondCardElement.classList.remove('flipped');
    
    // 扣分
    score = Math.max(0, score - 10); // 匹配错误扣10分，但不低于0
    document.getElementById('score').textContent = score;
    
    // 清空已翻转卡片数组
    flippedCards = [];
    isChecking = false;
}

// 更新计时器
function updateTimer() {
    elapsedTime = Math.floor((Date.now() - startTime) / 1000);
    document.getElementById('timer').textContent = formatTime(elapsedTime);
    
    // 检查游戏时间是否结束
    if (gameDuration > 0 && elapsedTime >= gameDuration) {
        gameOver();
    }
}

// 切换暂停状态
function togglePause() {
    if (isGameRunning) {
        pauseGame();
    } else {
        resumeGame();
    }
}

// 暂停游戏
function pauseGame() {
    clearInterval(timerInterval);
    isGameRunning = false;
    document.getElementById('pauseBtn').textContent = '继续';
    
    // 添加暂停视觉效果
    const gameContainer = document.getElementById('memoryGame');
    gameContainer.style.opacity = '0.6';
}

// 继续游戏
function resumeGame() {
    startTime = Date.now() - elapsedTime * 1000;
    timerInterval = setInterval(updateTimer, 1000);
    isGameRunning = true;
    document.getElementById('pauseBtn').textContent = '暂停';
    
    // 移除暂停视觉效果
    const gameContainer = document.getElementById('memoryGame');
    gameContainer.style.opacity = '1';
}

// 游戏完成
function gameComplete() {
    clearInterval(timerInterval);
    isGameRunning = false;
    
    document.getElementById('startBtn').disabled = false;
    document.getElementById('pauseBtn').disabled = true;
    document.getElementById('pauseBtn').textContent = '暂停';
    
    // 计算时间奖励（时间越少奖励越多）
    const timeBonus = Math.max(200 - elapsedTime * 2, 50);
    score += timeBonus;
    document.getElementById('score').textContent = score;
    
    // 记录分数
    recordScore('memory', score, elapsedTime);
    
    // 更新最高分
    document.getElementById('highScore').textContent = getHighScore('memory');
    
    // 显示游戏完成消息
    showMessage(`恭喜！游戏完成！得分：${score}，步数：${moves}，用时：${formatTime(elapsedTime)}`, 'success');
}

// 游戏结束（超时）
function gameOver() {
    clearInterval(timerInterval);
    isGameRunning = false;
    
    document.getElementById('startBtn').disabled = false;
    document.getElementById('pauseBtn').disabled = true;
    document.getElementById('pauseBtn').textContent = '暂停';
    
    // 记录分数
    recordScore('memory', score, elapsedTime);
    
    // 更新最高分
    document.getElementById('highScore').textContent = getHighScore('memory');
    
    // 显示游戏结束消息
    showMessage(`时间到！得分：${score}，已匹配：${matchedPairs}/${totalPairs}对`, 'error');
}

// 重置游戏
function resetGame() {
    clearInterval(timerInterval);
    isGameRunning = false;
    
    document.getElementById('startBtn').disabled = false;
    document.getElementById('pauseBtn').disabled = true;
    document.getElementById('pauseBtn').textContent = '暂停';
    
    // 重新创建卡片
    createCards();
}